<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, i) in arr" :key="item.id">
          <td>{{ i + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="delFn(item.id)">删除</button>
            <button @click="editFn(item, i)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      index: "",
      id: +new Date(),
      uname: "",
      age: "",
      sex: "",
      flag: false,
      arr: [
        {
          id: 0,
          uname: "Tom",
          age: 23,
          sex: "女",
        },
        {
          id: 1,
          uname: "Jone",
          age: 13,
          sex: "男",
        },
        {
          id: 2,
          uname: "Jane",
          age: 26,
          sex: "女",
        },
      ],
    };
  },
  methods: {
    //添加功能
    addFn() {
      // 当输入框没有值, 要给用户一个提示, 必须都有值才能增加新数据
      if (this.uname.length === 0 || this.age.length === 0) {
        return alert("请输入新增内容");
      }

      if (this.flag) {
        this.arr[this.index] = {
          id: this.id,
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        };
        this.flag = !this.flag;
      } else {
        // 给arr数组添加数据
        this.arr.push({
          id: this.id,
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        });
      }

      this.uname = "";
      this.age = "";
      this.sex = "";
    },

    // 编辑功能
    editFn(val, ind) {
      this.uname = val.uname;
      this.age = val.age;
      this.sex = val.sex;
      this.index = ind;
      this.flag = !this.flag;
    },

    // 删除功能
    delFn(id) {
      this.arr = this.arr.filter((item) => item.id !== id);
    },
  },
};
</script>
